// test_index.js - 测试加载索引文件
require('dotenv').config();
const { HNSWLib } = require("@langchain/community/vectorstores/hnswlib");
const { Embeddings } = require("@langchain/core/embeddings");
const path = require('path');

// 自定义嵌入类，使用固定向量
class FixedEmbeddings extends Embeddings {
    constructor(fields) {
        super(fields || {});
    }

    async embedDocuments(texts) {
        const embeddings = [];
        for (const text of texts) {
            const embedding = await this.embedQuery(text);
            embeddings.push(embedding);
        }
        return embeddings;
    }

    async embedQuery(text) {
        // 返回固定向量
        return Array.from({ length: 1536 }, () => 0.1);
    }
}

const VECTOR_STORE_PATH = path.join(__dirname, 'vector_store');
const embeddings = new FixedEmbeddings();

async function testIndex() {
    try {
        console.log("开始测试加载索引...");
        
        // 加载向量存储
        console.log("加载向量存储...");
        const vectorStore = await HNSWLib.load(VECTOR_STORE_PATH, embeddings);
        console.log("向量存储加载成功");
        
        // 测试搜索
        console.log("测试搜索...");
        const results = await vectorStore.similaritySearch("React Hooks", 2);
        
        console.log("搜索结果:");
        results.forEach((result, index) => {
            console.log(`结果 ${index + 1}: ${result.pageContent.substring(0, 100)}...`);
        });
        
        console.log("索引测试完成！");
        
    } catch (error) {
        console.error("测试索引失败:", error);
    }
}

// 运行测试
testIndex();